# -*- coding: utf-8 -*-
"""
Created on Thu Sep 30 11:31:11 2021

@author: 刘长奇-2019300677
"""

import pandas as pd
data = pd.read_csv ("dataset_circles.csv")
import numpy as np
import matplotlib.pyplot as plt
import random
x0,x1,y= np.loadtxt("dataset_circles.csv",delimiter=',', usecols=(0,1,2), 
	unpack=True)

num = np.shape (data) [0]

x0 = x0.reshape(-1,1)
x1 =x1.reshape(-1,1)
#样本数据的两个维度

y=y.reshape(-1,1)
#样本数据的类别

x = np.hstack((x0. reshape(-1,1) ,x1. reshape(-1, 1)))
plt.figure()
plt.scatter(x[:,0],x[:,1],c = y)
plt.title('initial data plot')
plt.colorbar
plt.show ()

#画出数据

#计算某一中心的欧氏距离和
def sum_distance(v1,v2):
    n=np.shape(v2)[0]
    for i in range(n):
        v2[i]=v2[i]-v1[0]     
    return np.sum(np.square(v2))

#计算两点之间距离
def distance(data1,data2):
    dis=(data1[0]-data2[0])**2+(data1[1]-data2[1])**2
    return dis

#产生随机中心
def rand_center (x,k):
    n=np.shape(x)[0]
    x00=[]
    x11=[]
    for i in range (k):
        x00.append(x[random.randint(0,n-1),0])
    for j in range(k):
        x11.append(x[random.randint(0,n-1),1])
    x00=np.array(x00)
    x11=np.array(x11)
    c = np.hstack((x00. reshape(-1,1) ,x11. reshape(-1, 1)))
    return c
        
#计算平均中心
def avg_center (m):
    ct=np.array([[0,0]])
    ct[0][0]=np.mean(m[:,0])
    ct[0][1]=np.mean(m[:,1])
    return ct

#二分类贴标签算法
def classify (ct,x,k):
    n=np.shape(x)[0]
    dis=np.zeros((np.shape(x)[0],np.shape(x)[1]))
    label=np.zeros(n)
    for i in range (n):
        for j in range(k):
            dis[i][j]=distance(x[i],ct[j])
    for i in range (n):
        if dis[i][0]<dis[i][1]:
            label[i]=0
        else:
            label[i]=1
    return label
    
#kmeans算法
m=np.shape(x)[0]
k=2
cs=0
ct_initial=rand_center(x,k)
mindistance=np.inf

while True:
    temp1=[]
    temp2=[]
    cpr=np.zeros((2,2))
    cpr[0]=ct_initial[0]
    cpr[1]=ct_initial[1]
    label=classify(ct_initial,x,k)
    for i in range(m):
        if label[i]==0:
            temp1.append(x[i])
        else:
            temp2.append(x[i])
    temp1=np.array(temp1)
    temp2=np.array(temp2)
    mindistance1=sum_distance(ct_initial[0], temp1)
    mindistance2=sum_distance(ct_initial[1],temp2)
    cs=cs+1
    mindistance=mindistance1+mindistance2
    ct_initial[0]=avg_center(temp1)
    ct_initial[1]=avg_center(temp2)
        
        
#误差要求
    if distance(cpr[0],ct_initial[0])==0 and distance(cpr[1],ct_initial[1])==0:
        plt.plot(ct_initial[0][0],ct_initial[0][1],'k*')
        plt.plot(ct_initial[1][0],ct_initial[1][1],'c^')
        plt.scatter(temp1[:,0],temp1[:,1],c='y')
        plt.scatter(temp2[:,0],temp2[:,1],c='b')
        plt.title('K-means')
        plt.show()
        print('迭代次数为：',cs)
        break

    
    
    
    